import request from "@/axios/request";

const {ElMessage} = require("element-plus");

export default {
    name: "LandlordTransactionRecord",
    data() {
        return {
            loading: true,
            landlordId: null,
            username: "",
            password: "",
            phone: "",
            email: "",
            currentPage: 1,
            pageSize: 10,
            total: 0,
            tenant_total: 0,
            transaction_total: 0,
            allTransactionData: [],
            tableTransactionData: [],
            allTenantData: [],
            tableTenantData: [],
            allData: [],       // 存储全量数据
            tableData: [],     // 当前页数据
            // allData: [{
            //     houseId: 1,
            //     title: "学院十一峯",
            //     description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处，由金地集团与新希望地产联合开发，2021年竣工交付。项目总户数1276户，包含11栋板塔结合建筑，绿化率30%，容积率3.13，物业费4.7元/㎡·月（含能耗费）。小区定位改善型住宅，主力户型为143-189㎡的四居室，南北通透设计，精装修交付。‌‌",
            //     price: "5000",
            //     address: "温州市鹿城区滨江街道会展路与学院路交汇处",
            //     area: "浙江省",
            //     size: 140,
            //     rooms: 3,
            //     floor: 3,
            //     landlordId: 1,
            //     status: "待审核",
            //     imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
            // }]
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allData.slice(start, end);
        },
        paginatedTenantData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allTenantData.slice(start, end);
        },
        paginatedTransactionData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allTransactionData.slice(start, end);
        }
    },
    created() {
        this.loadMyInfo();
        this.load();
        this.loading = true;
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    },
    methods: {
        async load() {
            try{
                // 获取所有房屋信息
                const res = await request.get("/house/findAll");
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.total = this.allData.length;
                    this.tableData = this.paginatedData;
                } else {
                    ElMessage.error(res.msg || "加载失败");
                    this.allData = [];
                    this.tableData = [];
                    this.total = 0;
                }
                // 获取所有租户信息
                const res_tenant = await request.get("/tenant/findAll");
                if (res_tenant.code === 200) {
                    this.allTenantData = res_tenant.data || [];
                    this.tenant_total = this.allTenantData.length;
                    this.tableTenantData = this.paginatedTenantData;
                } else {
                    ElMessage.error(res_tenant.msg || "加载失败");
                    this.allTenantData = [];
                    this.tableTenantData = [];
                    this.tenant_total = 0;
                }
                const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
                this.landlord = token.landlordId;
                // 获取所有交易信息
                const res_transaction = await request.get(`/record/landlord/${this.landlordId}`);
                if (res_transaction.code === 200) {
                    this.allTransactionData = res_transaction.data || [];
                    this.transaction_total = this.allTransactionData.length;
                    this.tableTransactionData = this.paginatedTransactionData;
                } else {
                    ElMessage.error(res_transaction.msg || "加载失败");
                    this.allTransactionData = [];
                    this.tableTransactionData = [];
                    this.transaction_total = 0;
                }
                this.loading = false;
            } catch (err){
                
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");

                this.allData = [];
                this.tableData = [];
                this.total = 0; 

                this.allTenantData = [];
                this.tableTenantData = [];
                this.tenant_total = 0;

                this.allTransactionData = [];
                this.tableTransactionData = [];
                this.transaction_total = 0;

                this.loading = false;
            }

        },
        loadMyInfo() {
            const token = JSON.parse(window.sessionStorage.getItem('userInfo'));

            if(!token) {
                ElMessage.error("获取用户信息失败");
                console.log("获取用户信息失败");
                return;
            }

            this.landlordId = token.landlordId;
            this.username = token.username;
            this.password = token.password;
            this.phone = token.phone;
            this.email = token.email;
        },
        SignOut() {
            sessionStorage.clear()
            ElMessage({
                message: '用户退出登录',
                type: 'success',
            });
            this.$router.replace({path: '/Login'});
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.tableData = this.paginatedData;
        },
        handleCurrentChange(pageNum) {
            this.currentPage = pageNum;
            this.tableData = this.paginatedData;
        },
        getTitle(houseId) {
            const house = this.allData.find(item => item.houseId === houseId);
            if (house.title === ""){
                return "未知名称";
            }
            return house.title;
        },
        getTenantUsername(tenantId) {
            const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
            if (tenant.username === ""){
                return "未知用户";
            }
            return tenant.username;
        },
        getTenantPhone(tenantId) {
            const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
            if (tenant.phone === ""){
                return "未知电话号码";
            }
            return tenant.phone;
        },
        getTenantEmail(tenantId) {
            const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
            if (tenant.email === ""){
                return "未知邮箱";
            }
            return tenant.email;
        },
        //时间显示
        formatTime(isoTime) {
        if (!isoTime) return "-";
        const date = new Date(isoTime);
        // 手动格式化避免浏览器差异
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        },
    },
};